package cn.edu.scnu.socialapp.controller;

import cn.edu.scnu.socialapp.model.entity.User;
import cn.edu.scnu.socialapp.model.vo.Result;
import cn.edu.scnu.socialapp.model.vo.UserVo;
import cn.edu.scnu.socialapp.model.vo.params.EmailCodeParams;
import cn.edu.scnu.socialapp.model.vo.params.LoginParams;
import cn.edu.scnu.socialapp.model.vo.params.RegisterParams;
import cn.edu.scnu.socialapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // users/currentUser
    @GetMapping("/currentUser")
    public Result currentUser(@RequestHeader("Authorization") String token) {
        return userService.findUserByToken(token);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginParams loginParams) {
        return userService.login(loginParams);
    }

    @GetMapping("/logout")
    public Result logout(@RequestHeader("Authorization") String token) {
        return userService.logout(token);
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterParams registerParams) {
        return userService.register(registerParams);
    }

    @PostMapping("/register/sendEmailCode")
    public Result sendEmailCode(@RequestBody EmailCodeParams emailCodeParams) {
        return userService.sendEmailCode(emailCodeParams);
    }

    @GetMapping("/getUserById/{id}")
    public User findUser(@PathVariable("id") Long userId) {
        return userService.findUserByUserId(userId);
    }

    @GetMapping("/getUserVoById/{id}")
    public UserVo findUserVo(@PathVariable("id") Long id) {
        return userService.findUserVoByUserId(id);
    }

    @GetMapping("/captcha/{uuid}")
    public void generateCaptcha(HttpServletResponse response, @PathVariable("uuid") String uuid) throws Exception {
        // 生成四位随机验证码
        String captcha = userService.generateRandomCaptcha(4);
//        String uuid = UUID.randomUUID().toString();
        // 将验证码存入redis，有效期为3分钟
        String redisKey = "PIC_CAPTCHA_" + uuid;
        redisTemplate.opsForValue().set(redisKey, captcha, 3, TimeUnit.MINUTES);
        // 生成验证码图片
        BufferedImage image = userService.generateCaptchaImage(captcha);
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        // 将验证码图片写入响应流
        ImageIO.write(image, "png", response.getOutputStream());
    }

}
